#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import re
import glob
from fm_util import Util
from usr_session import UsrSession


class FmUsrChecker:

    def __init__(self):
        self.infoPrinter = None
        self.bAutoFix = False

    def basicCheck(self):
        pass

    def fullCheck(self, bAutoFix, deepCheck):
        self.bAutoFix = bAutoFix
        self.infoPrinter = None

        self._checkSessionTypes()
        self._checkHomeDirPamCfg()
        self._checkHomeDirBashCfg()

    def _checkSessionTypes(self):
        # FIXME: should search all repositories, not only overlay-fpemud
        ret = []
        for fullfn in glob.glob("/var/lib/portage/overlay-fpemud/app-admin/fpemud-os-session-*-meta"):
            m = re.search(r"fpemud-os-session-(\S+)-(\S+)-(\S+)-meta$", fullfn)
            ret.append(m.group(1), m.group(2), m.group(3))

        if set(ret) != set(UsrSession.getAccessUiBusinessList()):
            # no way to auto-fix
            self.infoPrinter.printError("Session type meta packages are invalid.")

    def _checkHomeDirPamCfg(self):
        fullfn = os.path.expanduser("~/.pam_environment")
        if os.path.exists(fullfn):
            if self.bAutoFix:
                Util.forceDelete(fullfn)
            else:
                self.infoPrinter.printError("File ~/.pam_environment exists.")

    def _checkHomeDirBashCfg(self):
        fullfn = os.path.expanduser("~/.bash_profile")
        if os.path.exists(fullfn):
            if self.bAutoFix:
                Util.forceDelete(fullfn)
            else:
                self.infoPrinter.printError("File ~/.bash_profile exists.")
